// ignore_for_file: library_private_types_in_public_api, use_build_context_synchronously

import 'dart:io';
import 'package:number_paginator/number_paginator.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sp_util/sp_util.dart';
import 'package:syncfusion_flutter_datagrid_export/export.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart' as xlsio;
import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:storage/database.dart';
import 'package:storage/model/company_model_entity.dart';
import 'package:storage/source/all_company_source.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class AllCompanyPage extends StatefulWidget {
  const AllCompanyPage(
      {super.key, this.showButton = true, this.confirmCallBack});

  final bool showButton;
  final Function? confirmCallBack;

  @override
  _AllCompanyPageState createState() => _AllCompanyPageState();
}

class _AllCompanyPageState extends State<AllCompanyPage> {
  final GlobalKey<SfDataGridState> _key = GlobalKey<SfDataGridState>();

  List<CompanyModelEntity> modelList = [];
  late AllCompanyDataSource allCompanyDataSource;
  final TextEditingController _dialogController = TextEditingController();
  final TextEditingController _searchController = TextEditingController();

  @override
  void dispose() {
    _dialogController.dispose();
    _searchController.dispose();
    _controller.dispose();
    super.dispose();
  }

  bool needPage = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      needPage = SpUtil.getBool('needPage') ?? false;
      refreshData();
    });
  }

  int pageNum = 1;
  int pageSize = 20;
  int total = 0;

  Future<void> refreshData() async {
    CommonListModel result = await DatabaseHelper().getCompanyList(
        companyName: _searchController.text,
        pageNum: needPage ? pageNum : null,
        pageSize: needPage ? pageSize : null);
    total = (result.total / pageSize).ceil();
    if (result.data.isNotEmpty) {
      modelList =
          result.data.map((e) => CompanyModelEntity.fromJson(e)).toList();
      allCompanyDataSource = AllCompanyDataSource(employeeData: modelList);
    }

    setState(() {});
  }

  final NumberPaginatorController _controller = NumberPaginatorController();

  Widget _buildBottomNumberPagination() {
    return NumberPaginator(
      config: const NumberPaginatorUIConfig(
        mainAxisAlignment: MainAxisAlignment.center
      ),
      controller: _controller,
      // by default, the paginator shows numbers as center content
      numberPages: total,
      onPageChange: (int index) {
        pageNum = index + 1;
        refreshData();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('公司列表'),
      ),
      body: Container(
        color: Colors.white,
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
                child: Column(
              children: [
                if (widget.showButton)
                  Row(
                    children: [
                      SizedBox(
                        width: 200,
                        height: 40,

                        child: TextField(
                          controller: _searchController,
                          maxLines: 1,
                          onSubmitted: (value) {
                            refreshData();
                          },
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderSide: const BorderSide(
                                    width: 2.0, color: Colors.black),
                                // 边框样式
                                borderRadius:
                                    BorderRadius.circular(10.0), // 设置圆角半径
                              ),
                              hintText: '请输入公司名称搜索',
                              hintStyle: const TextStyle(color: Colors.grey)),
                        ),
                      ),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            /// 搜索
                            refreshData();
                          },
                          child: const Text('搜索')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            _searchController.clear();
                            refreshData();
                          },
                          child: const Text('重置')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            showAddDialog();
                          },
                          child: const Text('新增')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: selectedIdList.isEmpty
                              ? null
                              : () async {
                                  if (selectedIdList.isEmpty) {
                                    showToast('请选择需要删除的公司', context: context);
                                    return;
                                  }
                                  bool show = await deleteDialog();
                                  if (show) {
                                    await DatabaseHelper()
                                        .deleteCompany(selectedIdList);
                                    refreshData();
                                  }
                                },
                          child: const Text('删除')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            exportDataGridToExcel();
                          },
                          child: const Text('导出excel')),
                    ],
                  ),
                if (!widget.showButton)
                  FilledButton(
                      onPressed: selectedIdList.isEmpty
                          ? null
                          : () {
                              widget.confirmCallBack?.call(companyModelList);
                              Navigator.pop(context);
                            },
                      child: const Text('选中报价公司')),
                const SizedBox(height: 20),
                if (modelList.isNotEmpty)
                  Expanded(
                    child: SfDataGrid(
                      key: _key,
                      rowHeight: 40,
                      headerRowHeight: 40,
                      source: allCompanyDataSource,
                      columnWidthMode: ColumnWidthMode.fill,
                      showCheckboxColumn: true,
                      selectionMode: SelectionMode.multiple,
                      //开启列宽度调节
                      allowColumnsResizing: true,
                      onSelectionChanged: onSelectionChanged,
                      columns: <GridColumn>[
                        GridColumn(
                            columnName: '公司id',
                            label: Container(
                                padding: const EdgeInsets.all(8),
                                decoration: const BoxDecoration(
                                    color: Colors.lightBlueAccent,
                                    border: Border(
                                      right: BorderSide(
                                          color: Colors.grey, width: 1),
                                      left: BorderSide(
                                          color: Colors.grey, width: 1),
                                    )),
                                alignment: Alignment.center,
                                child: const Text(
                                  '公司id',
                                  style: TextStyle(color: Colors.white),
                                ))),
                        GridColumn(
                            columnName: '公司名称',
                            label: Container(
                                padding: const EdgeInsets.all(8),
                                decoration: const BoxDecoration(
                                    color: Colors.lightBlueAccent,
                                    border: Border(
                                      right: BorderSide(
                                          color: Colors.grey, width: 1),
                                      left: BorderSide(
                                          color: Colors.grey, width: 1),
                                    )),
                                alignment: Alignment.center,
                                child: const Text(
                                  '公司名称',
                                  style: TextStyle(color: Colors.white),
                                ))),
                      ],
                    ),
                  ),
              ],
            )),
            if (needPage&& total > 0) _buildBottomNumberPagination()
          ],
        ),
      ),
    );
  }

  List<int> selectedIdList = [];
  List<CompanyModelEntity> companyModelList = [];

  /// 导出excel
  Future<void> exportDataGridToExcel() async {
    // 获取当前应用的文档目录
    Directory documentsDirectory = await getApplicationDocumentsDirectory();

    // 创建一个名为“excel汇总”的子文件夹，如果不存在则创建
    Directory excelSummaryDirectory =
        Directory('${documentsDirectory.path}/excel汇总');
    if (!await excelSummaryDirectory.exists()) {
      await excelSummaryDirectory.create();
    }

    // 导出 SfDataGrid 数据到 Excel
    final xlsio.Workbook workbook = _key.currentState!.exportToExcelWorkbook(
      excludeColumns: ['公司id'],
    );
    final List<int> bytes = workbook.saveAsStream();
    workbook.dispose();

    // 生成唯一的文件名，避免覆盖同名文件
    String fileName = '公司列表_${DateTime.now().millisecondsSinceEpoch}.xlsx';
    File file = File('${excelSummaryDirectory.path}/$fileName');

    // 将文件写入到指定路径
    await file.writeAsBytes(bytes);

    showToast('公司列表导出成功', context: context);
  }

  // 表格选择事件改变回调
  void onSelectionChanged(
      List<DataGridRow> addedRows, List<DataGridRow> removedRows) {
    if (addedRows.isEmpty && removedRows.isEmpty) {
      for (DataGridRow row in allCompanyDataSource.rows) {
        int id = row.getCells().first.value as int;
        selectedIdList.remove(id);
        companyModelList
            .remove(modelList.firstWhere((element) => element.companyId == id));
      }
    }
    for (DataGridRow addedRow in addedRows) {
      int id = addedRow.getCells().first.value as int;
      if (!selectedIdList.contains(id)) {
        selectedIdList.add(id);
        companyModelList
            .add(modelList.firstWhere((element) => element.companyId == id));
      }
    }
    for (DataGridRow removedRow in removedRows) {
      int id = removedRow.getCells().first.value as int;
      companyModelList
          .remove(modelList.firstWhere((element) => element.companyId == id));
      selectedIdList.remove(id);
    }
    setState(() {});
  }

  /// 添加公司dialog
  void showAddDialog() {
    showDialog(
        context: context,
        builder: (_) => Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              elevation: 0, // 移除阴影以符合定制大小的需求
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 400,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(
                              child: TextField(
                            controller: _dialogController,
                            maxLines: 6,
                            decoration: InputDecoration(
                                border: OutlineInputBorder(
                                  borderSide: const BorderSide(
                                      width: 2.0, color: Colors.black),
                                  // 边框样式
                                  borderRadius:
                                      BorderRadius.circular(10.0), // 设置圆角半径
                                ),
                                hintText: '填写公司名称，多个公司时请用 、分开',
                                hintStyle: const TextStyle(color: Colors.grey)),
                          )),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    SizedBox(
                      width: 400,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(
                              child: FilledButton(
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                  child: const Text('取消'))),
                          const SizedBox(
                            width: 20,
                          ),
                          Expanded(
                              child: FilledButton(
                                  onPressed: () async {
                                    if (_dialogController.text.isNotEmpty) {
                                      List<String> tempList =
                                          _dialogController.text.split('、');
                                      await DatabaseHelper()
                                          .addCompany(tempList);

                                      _dialogController.clear();
                                      refreshData();
                                    }

                                    Navigator.pop(context);
                                  },
                                  child: const Text('确定'))),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ));
  }

  /// 删除dialog
  Future<bool> deleteDialog() async {
    bool returnValue = false;
    await showDialog(
        context: context,
        builder: (_) => Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              elevation: 0, // 移除阴影以符合定制大小的需求
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 200,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Text('是否确认删除'),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    SizedBox(
                      width: 200,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(
                              child: FilledButton(
                                  onPressed: () {
                                    Navigator.pop(context);
                                    returnValue = false;
                                  },
                                  child: const Text('取消'))),
                          const SizedBox(
                            width: 20,
                          ),
                          Expanded(
                              child: FilledButton(
                                  onPressed: () async {
                                    Navigator.pop(context);
                                    returnValue = true;
                                  },
                                  child: const Text('确定'))),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ));
    return returnValue;
  }
}
